package com.simple.crawler.core;

import com.simple.crawler.utils.CrawlerLogger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;

public class TaskExecutor implements Job {

    private static final CrawlerLogger logger = CrawlerLogger.getLogger(TaskExecutor.class);

    //等待队列
    private static final TaskQueue waitQueue = new TaskQueue();

    //执行队列
    private static final Set<Task> execQueue = new CopyOnWriteArraySet();

    @Override
    public void execute(JobExecutionContext context) {
        try {
            if (waitQueue.isEmpty() || execQueue.size() >= 5) {
                return;
            }
            Task task = waitQueue.pop();
            execQueue.add(task);
            task.run();
            execQueue.remove(task);
        } catch (Exception e) {
            logger.error("执行任务出错:{}", e.getLocalizedMessage());
        }
    }

    public static void addTask(Task task) {
        waitQueue.add(task);
    }

    public static void addTask(Task... task) {
        waitQueue.addAll(Arrays.asList(task));
    }

    public static TaskQueue getWaitQueue() {
        return waitQueue;
    }

    public static Set<Task> getExecQueue() {
        return execQueue;
    }
}
